﻿using NAudio.CoreAudioApi;
using NAudio.Wave;
using Newtonsoft.Json;
using QTFS.ViewModels;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using TagLib;

namespace QTFS.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private AudioFileReader _audioFileReader;
        private IWavePlayer _wavePlayer;

        // 定时器：用于实时更新进度
        private readonly DispatcherTimer _progressTimer;
        private readonly Stopwatch _stopwatch;

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new MusicListModel();
            // 初始化定时器
            _stopwatch = new Stopwatch();
            _stopwatch.Reset();
        }

        private void ListView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // 双击需要先清理播放缓存，从新的开始播放
            _audioFileReader?.Dispose();
            if (_wavePlayer != null)
            {
                _wavePlayer.PlaybackStopped -= _wavePlayer_PlaybackStopped;
                _wavePlayer.Dispose();
            }
            var item = (ListBox)sender;
            var itemData = item.SelectedItem.ToString(); // 获取项目中的数据

            var item_DataContext = JsonConvert.SerializeObject(item.DataContext);

            var filePath = $"{JsonConvert.DeserializeObject<MusicListModel>(item_DataContext).ListPath}{itemData}";
            _audioFileReader = new AudioFileReader(filePath);

            _wavePlayer = new WaveOutEvent();
            _wavePlayer.Init(_audioFileReader);

            LoadAlbumCoverWithTagLib(filePath);

            Play();
        }

        /// <summary>
        /// 传入音频文件路径，返回封面图片（绑定到 Image 控件）
        /// </summary>
        /// <param name="audioFilePath"></param>
        private void LoadAlbumCoverWithTagLib(string audioFilePath)
        {
            // 1. 打开音频文件（支持 MP3、FLAC、AAC 等）
            using (var audioFile = TagLib.File.Create(audioFilePath))
            {
                // 2. 检查是否包含封面图片（Pictures 集合存储所有图片元数据）
                if (audioFile.Tag.Pictures.Length > 0)
                {
                    // 3. 提取第一张封面（通常索引 0 是主封面）
                    var coverData = audioFile.Tag.Pictures[0].Data.Data; // 获取图片二进制数据
                    var coverStream = new MemoryStream(coverData); // 转为内存流

                    // 4. 转为 WPF 支持的 BitmapImage 格式
                    var coverImage = new BitmapImage();
                    coverImage.BeginInit();
                    coverImage.StreamSource = coverStream;
                    coverImage.CacheOption = BitmapCacheOption.OnLoad; // 避免流关闭后图片失效
                    coverImage.EndInit();

                    // 5. 绑定到界面 Image 控件（假设控件名是 imgAlbumCover）
                    imgAlbumCover.Source = coverImage;
                }
                else
                {
                    // 处理无封面的情况（显示默认图片）
                    imgAlbumCover.Source = new BitmapImage(new Uri("/Assets/Images/音乐.png"));
                }
            }
        }


        private void progressBar_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

        }


        /// <summary>
        /// 播放音乐
        /// </summary>
        /// <param name="sender"></param>
        private void Play()
        {
            if (_wavePlayer != null)
            {
                _wavePlayer.Play();
                _stopwatch.Start();
                _wavePlayer.PlaybackStopped += _wavePlayer_PlaybackStopped;
            }
        }

        /// <summary>
        /// 暂停音乐
        /// </summary>
        private void Pause()
        {
            if (_wavePlayer != null)
            {
                _wavePlayer.PlaybackStopped -= _wavePlayer_PlaybackStopped;
                _wavePlayer.Pause();
                _stopwatch.Stop();
            }
        }

        /// <summary>
        /// 定时器事件：更新进度条和时间显示
        /// </summary>
        private void ProgressTimer_Tick()
        {
            if (_wavePlayer.PlaybackState == PlaybackState.Playing)
            {
                // 计算当前进度比例（0-1）

                // 更新时间显示（格式：当前时间 / 总时长）
                timeLabel.Text = $"{_audioFileReader:mm\\:ss}/{_audioFileReader.TotalTime:mm\\:ss}";
            }
        }

        private void _wavePlayer_PlaybackStopped(object? sender, StoppedEventArgs e)
        {
            _wavePlayer?.Stop();
            if (_audioFileReader != null) _audioFileReader.Position = 0;
        }

        private void ClickPause(object sender, RoutedEventArgs e)
        {
            Pause();
        }

        private void ClickPlay(object sender, RoutedEventArgs e)
        {
            Play();
        }
    }
}